package pkg

import (
	"context"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"log"
	"mime/multipart"
	"regexp"
)

// ValidatePhone 验证手机号格式
func ValidatePhone(mobile string) bool {
	// 手机号正则表达式，支持中国大陆手机号码
	// 规则：1开头，第二位3-9，后面跟9位数字
	reg := `^1[3-9]\d{9}$`
	match, _ := regexp.MatchString(reg, mobile)
	return match
}

func ValidateMobile(mobile string) bool {
	if !ValidatePhone(mobile) {
		return false
	}
	return true
}

/*
如果使用minio上传,必须先在client层新建tmp包
file, _ := c.FormFile("file")
if file.Size >= 500*1024*1024 {
c.JSON(200, gin.H{
"code": 10001,
"msg":  "The file is too large, and only files within 500MB are allowed to be uploaded.",
"data": nil,
})
return
}
ext := filepath.Ext(file.Filename)
if ext != ".mp4" {
c.JSON(200, gin.H{
"code": 10002,
"msg":  "The file only supports mp4 format.",
"data": nil,
})
return
}

fileName := time.Now().Format(time.DateTime) + ext
open, err := file.Open()
if err != nil {
log.Println("file open error")
return
}
defer open.Close()
if !utils.MiNio(fileName, open) {
c.JSON(200, gin.H{
"code": 10003,
"msg":  "File upload failed.",
"data": nil,
})
return
}
c.JSON(200, gin.H{
"code": 200,
"msg":  "File upload successfully.",
"data": nil,
})
*/
func MiNios(name string, open multipart.File) bool {
	// MinIO 服务器配置
	AppConf := config.AppConf.MiNio
	endpoint := AppConf.Endpoint
	accessKeyID := AppConf.AccesskeyId
	secretAccessKey := AppConf.AccesskeySecret

	// 文件配置
	fileName := name                 // 要上传的文件名
	bucketName := AppConf.BucketName // 目标桶名
	objectName := fileName           // 上传后对象的名称（可包含路径前缀）
	contentType := "text/plain"      // 文件的 MIME 类型

	// 初始化 MinIO 客户端
	minioClient, err := minio.New(endpoint, &minio.Options{
		Creds:  credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
		Secure: false,
	})
	if err != nil {
		log.Fatalln(err)
	}

	// 创建上下文
	ctx := context.Background()

	// 创建桶（如果不存在）
	location := "test"
	err = minioClient.MakeBucket(ctx, bucketName, minio.MakeBucketOptions{Region: location})
	if err != nil {
		exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
		if errBucketExists != nil {
			log.Fatalln(errBucketExists)
		}
		if exists {
			log.Printf("Bucket %s already exists", bucketName)
		} else {
			log.Fatalln(err)
		}
	} else {
		log.Printf("Successfully created bucket %s", bucketName)
	}

	// 上传文件
	//filePath := filepath.Join("./tmp/", fileName) // 文件路径
	//fmt.Println(filePath)
	_, err = minioClient.PutObject(ctx, bucketName, objectName, open, -1, minio.PutObjectOptions{ContentType: contentType})
	log.Println(objectName)
	if err != nil {
		log.Printf("Failed to upload %s: %v", objectName, err)
		return false
	}

	log.Printf("Successfully uploaded %s%s", AppConf.BucketUrl, fileName)
	return true
}
